package com.daxing.publishconfirm;
import com.daxing.utils.ConnectionUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmListener;
import com.rabbitmq.client.Connection;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class SenderAsync {
    private static final String EXCHANGENAME = "routingexchange";

    public static void main(String[] args) throws Exception {
        //获取连接
        Connection connection = ConnectionUtils.getConnection();
        //声明通道,就类似于数据库的statment
        Channel channel = connection.createChannel();
        //声明交换机
        channel.exchangeDeclare(EXCHANGENAME, "direct");
        channel.confirmSelect();//开启发布确认
        //异步接收发布确认结果
        channel.addConfirmListener(new ConfirmListener() {
            @Override
            public void handleAck(long deliveryTag, boolean multiple) throws IOException {
                System.err.println("发送成功");
            }

            @Override
            public void handleNack(long deliveryTag, boolean multiple) throws IOException {
                System.err.println("fasong失败");
            }
        });
        //发送消息
        String msg = "感觉自己被骗了";

        for (int i = 0; i < 100; i++) {
            channel.basicPublish(EXCHANGENAME, "saoma", null, (msg + i).getBytes(StandardCharsets.UTF_8));
        }

//        在开启了异步确认和return的时候不能关闭连接
        //  channel.close();
        //  connection.close();
    }
}
